package model

import (
	"fmt"
	"github.com/gookit/color"
	"github.com/jinzhu/gorm"
	"go-car/pkg/setting"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var (
	DB *gorm.DB
)

func Setup() {
	var err error
	addr := fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True",
		setting.DatabaseSetting.Username,
		setting.DatabaseSetting.Password,
		setting.DatabaseSetting.DbName)
	DB, err = gorm.Open("mysql", addr)
	if err != nil {
		color.Error.Printf("init db err: %v\n", err)
	}

	DB.SingularTable(true)
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return setting.DatabaseSetting.TablePrefix + defaultTableName
	}
}

func AddCars(cars []QcCar) {
	for i, car := range cars {
		if err := DB.Create(&car).Error; err != nil {
			color.Error.Printf("db.Create index: %d ,err: %v\n", i, err)
		}
	}
}
